package com.kun.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import com.kun.entity.UserLikeComment;
import com.kun.entity.UserLikeCommentExample;
import com.kun.entity.UserLikeCommentExample.Criteria;
import com.kun.mapper.master.MasterUserLikeCommentMapper;
import com.kun.mapper.master.custom.CommentMapperWCustom;
import com.kun.service.UserLikeCommentService;


/**
 * @description: 点赞redis 业务类
 * @author: KM
 * 2018年4月17日 下午5:25:14
 */
@Service
public class UserLikeCommentServiceImpl implements UserLikeCommentService {
	
	@Autowired 
	private MasterUserLikeCommentMapper masterUserLikeCommentMapper;
	
	@Autowired 
	private CommentMapperWCustom commentMapperWCustom;
	
	@Autowired
	private SetOperations<String, Object> setOperations;
	
	@Autowired
	private HashOperations<String, String, Object> hashOperations;
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	//存放所有有点赞操作的评论id (COMMENT_SET, comment_id)
	private static final String COMMENT_SET = "COMMENT_SET";
	
	//将每个用户对每个comment的点赞情况放到一个set里面去  (USER_LIKE_COMMENT+"comment_id"+"user_id",state)
	private static final String USER_LIKE_COMMENT_ = "USER_LIKE_COMMENT_";
	
	
	public int addSet(String userId,int commentId,String value){
		redisTemplate.setValueSerializer(new StringRedisSerializer());
		setOperations.add(COMMENT_SET, commentId+"");//存入评论id
		if(!hashOperations.hasKey(USER_LIKE_COMMENT_+commentId, userId)){//是否存在commentId-userId
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("state", value);
			map.put("likeTime",new Date());
			hashOperations.put(USER_LIKE_COMMENT_+commentId, userId, map);//不存在则存入用户id 和 操作
		}else{
			hashOperations.delete(USER_LIKE_COMMENT_+commentId, userId);//存在则抵消操作
		}
		//点赞计数器
		if("0".equals(value)){
			redisTemplate.opsForValue().increment("post_counter_"+commentId, -1);
		}else if("1".equals(value)){
			redisTemplate.opsForValue().increment("post_counter_"+commentId, 1);
		}
		return 1;
	}
	
	//定时任务同步redis点赞数据到数据库
	public String SchudelSync(){
		 redisTemplate.setValueSerializer(new StringRedisSerializer());
		 Set<Object> comment_set = setOperations.members(COMMENT_SET);//取出有操作的评论id集合
		 int before = 0;
		 Iterator<Object> it = comment_set.iterator();//迭代集合
		 while(it.hasNext()){
			 Object itObj = it.next();
			 int commentId = Integer.parseInt((String)itObj);//拿到评论id
			 Set<String> userIdSet = hashOperations.keys(USER_LIKE_COMMENT_+commentId);
			 Iterator<String> uit = userIdSet.iterator();
			 while(uit.hasNext()){//遍历评论id对应的  用户点赞操作hash
				 String userId = uit.next();
				 @SuppressWarnings("unchecked")
				 Map<String,Object> map = (Map<String,Object>)hashOperations.get(USER_LIKE_COMMENT_+commentId, userId);
				 if(map!=null&&!map.isEmpty()){
					 String state = (String)map.get("state");
					 Date likeTime = (Date)map.get("likeTime");
					 if("0".equals(state)){//取消点赞
						 UserLikeCommentExample ue = new UserLikeCommentExample();
						 Criteria c = ue.createCriteria();
						 c.andCommentIdEqualTo(commentId);
						 c.andUserIdEqualTo(userId);
						 c.andStateEqualTo("1");
						 masterUserLikeCommentMapper.deleteByExample(ue);
					 }else if("1".equals(state)){//点赞
						 UserLikeComment ulc = new UserLikeComment(commentId,userId,state,likeTime);
						 masterUserLikeCommentMapper.insertSelective(ulc);//插入用户点赞记录表
					 }
				 }
				 //更新完删除redis对应数据
				 hashOperations.delete(USER_LIKE_COMMENT_+commentId, userId);
				 before++;
			 }
			 //获取该评论最新的点赞数
			 String n = (String)redisTemplate.opsForValue().get("post_counter_"+commentId);
			 if(n!=null){
				 Integer number = Integer.parseInt(n);
				 if(number!=null){
					 commentMapperWCustom.updateLikesByParmaryKey(commentId, number);//把redis的数据更新入 数据库
					 redisTemplate.opsForValue().set("post_counter_"+commentId, "0");//redis置空
				 }
			 }
			 //更新完删除redis对应数据
			 setOperations.remove(COMMENT_SET, itObj);
		 }
		 return "成功同步" + before + "条评论的点赞数据";
	}
	
	//删除评论对应点赞
	public int deleteLikeInfo(int commentId){
		int i = 0;
		UserLikeCommentExample example = new UserLikeCommentExample();
		Criteria c = example.createCriteria();
		c.andCommentIdEqualTo(commentId);
		masterUserLikeCommentMapper.deleteByExample(example);
		setOperations.remove(COMMENT_SET, commentId);
		redisTemplate.delete(USER_LIKE_COMMENT_+commentId);
		redisTemplate.delete("post_counter_"+commentId);
		i = 1;
		return i;
	}
}
